package java8.stream.utility;// Returns the power set of an input set as custom collection

import java.util.*;

/**
 * 求数组的所有子集
 * 根据位运算 因为数组所有子集数量为 2的n次方个。
 * 0
 * 1
 * 10
 * 11
 * 100
 * 101
 * 110
 * 111
 * 利用等于1的位置存在数据值 例如
 * 输入 [a,b,c]  入参为 101 那么返回子集为 [a,c]
 */
public class PowerSet {
    public static final <E> Collection<Set<E>> of(Set<E> s) {
        List<E> src = new ArrayList<>(s);
        if (src.size() > 30)
            throw new IllegalArgumentException("Set too big " + s);

        return new AbstractList<Set<E>>() {
            @Override
            public int size() {
                return 1 << src.size(); // 2 to the power srcSize
            }

            @Override
            public boolean contains(Object o) {
                return o instanceof Set && src.containsAll((Set) o);
            }

            @Override
            public Set<E> get(int index) {
                Set<E> result = new HashSet<>();
                for (int i = 0; index != 0; i++, index >>= 1)
                    if ((index & 1) == 1)
                        result.add(src.get(i));
                return result;
            }
        };
    }


    public static void main(String[] args) {
     /*   Set s = Set.of("a", "b", "c","d");
        Collection collection = PowerSet.of(s);
        for (Object c : collection) {
           System.out.println(c);
        }*/
    }
}